<template>
  <div class="role-management">
    <div class="page-header">
      <h2>角色管理</h2>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :model="searchForm" inline>
        <el-form-item label="角色名称">
          <el-input v-model="searchForm.name" placeholder="请输入角色名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 角色表格 -->
    <div class="table-container">
      <el-table :data="tableData" v-loading="loading" border stripe :table-layout="'auto'">
        <el-table-column prop="id" label="ID" width="50" />
        <el-table-column prop="name" label="角色名称" width="100" />
        <!-- <el-table-column prop="code" label="角色编码" width="100" /> -->
        <el-table-column label="描述" min-width="120">
          <template #default="{ row }">
            <div class="description-cell">
              {{ row.description }}
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column label="权限数量" width="100">
          <template #default="{ row }">
            <el-tag 
              type="info" 
              size="small" 
              class="permission-count-tag"
              @click="handleViewPermissions(row)"
            >
              {{ row.permissions?.length || 0 }} 个权限
            </el-tag>
          </template>
        </el-table-column> -->
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <div class="status-control">
              <el-switch v-model="row.isActive" :active-value="true" :inactive-value="false"
                @change="handleToggleStatus(row)" :loading="toggleLoading" />
              <span class="status-text">
                {{ row.isActive ? '启用' : '禁用' }}
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="170">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="修改时间" width="170">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="170" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)" icon="Edit" type="primary">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)" :disabled="row.code === 'SuperAdmin'"
              icon="Delete">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination :current-page="pagination.page" :page-size="pagination.pageSize" :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
        @current-change="handlePageChange" />
    </div>

    <!-- 编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px" :before-close="handleCloseDialog">
      <el-form ref="roleForm" :model="roleFormData" :rules="roleFormRules" label-width="80px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleFormData.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="roleFormData.description" type="textarea" :rows="3" placeholder="请输入角色描述" />
        </el-form-item>
        <el-form-item label="菜单权限" prop="menus">
          <div class="permission-tree">
            <el-tree ref="menuTreeRef" :data="menuList" :props="treeProps" show-checkbox node-key="id"
              :default-expand-all="true" :check-strictly="false" @check="handleMenuCheck" />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleCloseDialog">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确认
        </el-button>
      </template>
    </el-dialog>

    <!-- 权限详情弹窗 -->
    <!-- <el-dialog
      v-model="permissionDialogVisible"
      title="权限详情"
      width="500px"
      :before-close="() => permissionDialogVisible = false"
    >
      <div v-if="currentRole">
        <h4 style="margin-bottom: 16px; color: #409eff;">{{ currentRole.name }} - 权限详情</h4>
        <el-tree
          :data="currentRolePermissions"
          node-key="id"
          :props="{ children: 'children', label: 'name' }"
          :default-expand-all="true"
          :expand-on-click-node="false"
          :highlight-current="false"
          :show-checkbox="false"
          style="max-height: 400px; overflow-y: auto;"
        >
          <template #default="{ data }">
            <span class="permission-tree-node">
              <el-icon v-if="data.icon" :size="16" style="margin-right: 8px;">
                <component :is="data.icon" />
              </el-icon>
              <span>{{ data.name }}</span>
              <el-tag 
                v-if="data.type" 
                :type="data.type === 'menu' ? 'primary' : 'success'"
                size="small"
                style="margin-left: 8px;"
              >
                {{ data.type === 'menu' ? '菜单' : '按钮' }}
              </el-tag>
            </span>
          </template>
        </el-tree>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog> -->
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { useRoleStore } from '@/stores/role'
import { useMenuStore } from '@/stores/menu'
// 响应式数据
const loading = ref(false)
const tableData = ref([])
const dialogVisible = ref(false)
const submitLoading = ref(false)
const isEdit = ref(false)
const currentRole = ref(null)
const roleForm = ref()
const useStore = useRoleStore();
const menuTreeRef = ref()
const menuList = ref([])
const menuStore = useMenuStore()
// 搜索表单
const searchForm = reactive({
  name: ''
})

// 分页数据
const pagination = ref({
  page: 1,
  pageSize: 10,
  total: 0
})

// 角色表单数据
const roleFormData = reactive({
  id: null,
  name: '',
  description: '',
  isActive: true,
  menuIds: []
})

// 树形控件属性
const treeProps = {
  children: 'children',
  label: 'name'
}
// 计算属性
const dialogTitle = computed(() => isEdit.value ? '编辑角色' : '新增角色')
const handleMenuCheck = () => {
  // 获取选中的菜单ID
  const checkedKeys = menuTreeRef.value.getCheckedKeys()
  const halfCheckedKeys = menuTreeRef.value.getHalfCheckedKeys()
  roleFormData.menuIds = [...checkedKeys, ...halfCheckedKeys]
}
// 表单验证规则
const roleFormRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '角色名称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/, message: '角色编码只能包含字母、数字和下划线，且以字母开头', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '描述不能超过200个字符', trigger: 'blur' }
  ]
}
const loadMenus = async () => {
  try {
    // 模拟API调用获取菜单列表
    const res = await menuStore.getmenutree()
    menuList.value = res
    console.log('菜单列表加载完成')
  } catch (error) {
    console.error('加载菜单失败:', error)
    ElMessage.error('加载菜单列表失败')
  }
}
// // 模拟权限树数据
// const permissionTreeData = computed(async () => {
//   return await menuStore.getmenutree()
// })
// const permissionTreeData1 = ref([
//   {
//     id: 1,
//     name: '用户管理',
//     type: 'menu',
//     children: [
//       { id: 11, name: '查看用户', type: 'permission' },
//       { id: 12, name: '新增用户', type: 'permission' },
//       { id: 13, name: '编辑用户', type: 'permission' },
//       { id: 14, name: '删除用户', type: 'permission' }
//     ]
//   },
//   {
//     id: 2,
//     name: '角色管理',
//     type: 'menu',
//     children: [
//       { id: 21, name: '查看角色', type: 'permission' },
//       { id: 22, name: '新增角色', type: 'permission' },
//       { id: 23, name: '编辑角色', type: 'permission' },
//       { id: 24, name: '删除角色', type: 'permission' }
//     ]
//   },
//   {
//     id: 3,
//     name: '菜单管理',
//     type: 'menu',
//     children: [
//       { id: 31, name: '查看菜单', type: 'permission' },
//       { id: 32, name: '新增菜单', type: 'permission' },
//       { id: 33, name: '编辑菜单', type: 'permission' },
//       { id: 34, name: '删除菜单', type: 'permission' }
//     ]
//   },
//   {
//     id: 4,
//     name: '系统设置',
//     type: 'menu',
//     children: [
//       { id: 41, name: '系统配置', type: 'permission' },
//       { id: 42, name: '数据备份', type: 'permission' },
//       { id: 43, name: '系统监控', type: 'permission' }
//     ]
//   }
// ])

// 方法
const loadData = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.value.page,
      pageSize: pagination.value.pageSize,
      keyword: searchForm.name?.trim() || undefined
    };
    console.log('搜索参数:', params);
    
    const response = await useStore.getRoles(params);
    console.log('API响应:', response);
    
    // 更新表格数据和分页信息
    tableData.value = response.roles;
    pagination.value = response.pagination;
  } catch (error) {
    console.error('加载数据失败:', error);
    ElMessage.error('加载数据失败: ' + (error.message || '未知错误'));
  } finally {
    loading.value = false;
  }
}
// 点击搜索，调用后端 API
const handleSearch = async () => {
  // 设置到第一页
  pagination.value.page = 1;
  // 调用加载数据，包含搜索关键字
  await loadData();
}


// 重置搜索条件
const handleReset = () => {
  searchForm.name = '';
  pagination.value.page = 1;
  loadData();
  ElMessage.success('搜索条件已重置');
}
//格式化日期
const formatDate = (time) => {
  if (!time) return '';
  const date = new Date(time);
  const beijingTime = new Date(date.getTime() + 8 * 3600 * 1000); // 转换为北京时间
  return beijingTime.toISOString().replace('T', ' ').substring(0, 19); // 格式化为 YYYY-MM-DD HH:MM:SS
};

//编辑表单数据获取
const handleEdit = (row) => {
  isEdit.value = true
  currentRole.value = row
  Object.assign(roleFormData, {
    id: row.id,
    name: row.name,
    isActive: row.isActive,
    description: row.description,
    menuIds: row.menuIds || []
  })
  dialogVisible.value = true
}
//删除角色√
const handleDelete = async (row) => {
  if (row.name === 'SuperAdmin') {
    ElMessage.warning('超级管理员角色不能删除')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除角色 "${row.name}" 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 使用 store 方法删除角色
    await useStore.deleteRole(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch {
    ElMessage.error('删除失败')
  }
}
const toggleLoading = ref(false);


// 切换状态
const handleToggleStatus = async (row) => {
  // 保存原始状态，以便失败时恢复
  const originalStatus = !row.isActive;
  const newStatus = row.isActive;
  const action = newStatus ? '启用' : '禁用';

  try {
    // 调用接口更新状态
    await useStore.editRole(row.id, {
      id: row.id,
      name: row.name,
      description: row.description,
      isActive: newStatus,
      menuIds: row.menuIds || []
    });

    ElMessage.success(`${action}成功`);
    
    // 更新本地数据中对应行的状态，避免重新加载整个列表
    const index = tableData.value.findIndex(item => item.id === row.id);
    if (index !== -1) {
      tableData.value[index].isActive = newStatus;
    }
  } catch (error) {
    // 如果操作失败，恢复原来的状态
    row.isActive = originalStatus;
    ElMessage.error(`${action}失败: ${error.message}`);
  }
};
//确认编辑√
const handleSubmit = async () => {
  try {
    // 表单验证
    // await roleFormRef.value.validate()

    // 检查是否选择了菜单权限
    if (roleFormData.menuIds.length === 0) {
      ElMessage.warning('请至少选择一个菜单权限')
      return
    }

    loading.value = true
    await useStore.editRole(roleFormData.id, roleFormData)
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
    dialogVisible.value = false
    loadData()
  } catch (error) {
    console.log('Validation failed:', error)
  } finally {
    submitLoading.value = false
  }
}


const handleCloseDialog = () => {
  dialogVisible.value = false
  resetFormData()
  if (roleForm.value) {
    roleForm.value.resetFields()
  }
}

const resetFormData = () => {
  Object.assign(roleFormData, {
    name: '',
    code: '',
    description: '',
    menuIds: []
  })
}

const handleSizeChange = (val) => {
  pagination.value.pageSize = val
  pagination.value.page = 1
  loadData()
}

const handlePageChange = (val) => {
  pagination.value.page = val
  loadData()
}
// 生命周期
onMounted(() => {
  loadData()
  loadMenus()
  // loadMenuData()
})
</script>

<style scoped>
.role-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.search-bar {
  background: #f5f5f5;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.table-container {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
}

.permission-tree {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  max-height: 300px;
  overflow-y: auto;
}

.status-control {
  display: flex;
  align-items: center;
  gap: 8px;
  justify-content: center;
}

.status-text {
  font-size: 12px;
  color: #606266;
  min-width: 24px;
}

.description-cell {
  white-space: normal;
  word-wrap: break-word;
  word-break: break-all;
  line-height: 1.5;
  max-height: 60px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
}

:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #eee;
  padding-bottom: 15px;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-tree-node__content) {
  height: 32px;
}

.permission-count-tag {
  cursor: pointer;
  transition: all 0.3s;
}

.permission-count-tag:hover {
  background-color: #79bbff;
  border-color: #79bbff;
  color: white;
}

.permission-tree-node {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #606266;
}
</style>
